package com.tanhua.mogon.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.api.MovementApi;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import com.tanhua.mogon.utils.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MovementTimeLineService movementTimeLineService;

    /**
     * 发布动态内容
     *
     * @param movement
     */
    @Override
    public void save(Movement movement) {
        //1.保存动态内容
        //设置Pid
        movement.setPid(idWorker.getNextId("movement"));
        //设置时间
        movement.setCreated(System.currentTimeMillis());
        //保存数据
        mongoTemplate.save(movement);

//        //2.查询当前用户id的好友数据
//        Criteria criteria = Criteria.where("userId").is(movement.getUserId());
//        Query query = Query.query(criteria);
//        List<Friend> friends = mongoTemplate.find(query, Friend.class);
//
//        //3.循环好友数据，构建好友时间数据表存入数据库
//        for (Friend friend : friends) {
//            //3.1创建好友时间表对象
//            MovementTimeLine movementTimeLine = new MovementTimeLine();
//            //3.2封装对象
//            //封装某一条动态的id
//            movementTimeLine.setMovementId(movement.getId());
//            //封装发布改动态的用户Id
//            movementTimeLine.setUserId(friend.getUserId());
//            //封装该用户好友的id
//            movementTimeLine.setFriendId(friend.getFriendId());
//            //封装时间线
//            movementTimeLine.setCreated(System.currentTimeMillis());
//            //3.3调用方法，把数据存储到数据库中
//            mongoTemplate.save(movementTimeLine);
//        }

        //通过异步处理，来存时间表数据
        movementTimeLineService.saveMovementTimeLine(movement);


    }


    /**
     * 查询用户动态
     *
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult<Movement> findByUserIdMovement(Long userId, Integer page, Integer pagesize) {
        //1.根据用户id查询
        Query query = Query.query(Criteria.where("userId").is(userId));

        //2.查询该用户的总动态条数
        long count = mongoTemplate.count(query, Movement.class);

        //3.设置分页条件和排序（按照创建时间排序）
        query.skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));

        //进行分页查询
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);

        return new PageResult<>(page, pagesize, (int) count, movementList);
    }


    /**
     * 查询好友动态（根据当前用户id匹配friend表中的friend字段名，查询到该用户的全部好友信息）
     *
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Movement> findFriendMovements(Long userId, Integer page, Integer pagesize) {
        //1.根据用户id查询时间线表
        Query query = Query.query(Criteria.where("friendId").is(userId))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);

        //2.获取动态id列表
        List<ObjectId> idList = movementTimeLines.stream().map(MovementTimeLine::getMovementId).collect(Collectors.toList());

        //3.根据动态id查询好友的动态详情
        Query query1 = Query.query(Criteria.where("id").in(idList));

        return mongoTemplate.find(query1, Movement.class);
    }


    /**
     * 随机推荐数据，并查询其动态
     *
     * @return
     */
    @Override
    public List<Movement> randomMovements() {
        //1 创建统计对象,设置需要10个样本
        TypedAggregation<Movement> movementTypedAggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(10));

        //2. 调用MongoDB的统计方法获取结果
        AggregationResults<Movement> results = mongoTemplate.aggregate(movementTypedAggregation, Movement.class);

        //3. 获取统计结果
        List<Movement> list = results.getMappedResults();

        return list;
    }


    /**
     * 根据推荐数据查询动态
     *
     * @param pidList
     * @return
     */
    @Override
    public List<Movement> findByPids(List<Long> pidList) {
        //1.构建查询条件
        Query query = Query.query(Criteria.where("pid").in(pidList));

        //2.查询并返回
        return mongoTemplate.find(query, Movement.class);
    }


    /**
     * 根据动态id查询动态你详情
     *
     * @param movementId
     * @return
     */
    @Override
    public Movement findMovementByMovementId(String movementId) {
        Movement movement = mongoTemplate.findById(new ObjectId(movementId), Movement.class);
//        //1.构建查询条件
//        Query query = Query.query(Criteria.where("id").is(movementId));
//
//        //2.执行查询并返回
//        Movement movement = mongoTemplate.findOne(query, Movement.class);
        return movement;
    }
}
